<!doctype html>
<html>
<head>
<meta name="viewport" content="user-scalable=no, width=device-width, height=device-height">
<title>PowPow Controls</title>
<style>
html, body {
  width: 100%;
  height: 100%;
  border: 0px;
  padding: 0px;
  margin: 0px;
  background-color: black; /* blue; */
  font-family: sans-serif;
}
.instruction {
  color: rgba(255,255,255,0.7);
}
#surface {
  width: 100%;
  height: 100%;
  gbackground-color: green;
  gbackground-image: url(assets/waiting.png);
}
#status {
  gbackground-color: red;
  width: 100%;
  height: 300px;
  overflow: auto;
}
#touchControls {
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 2;
  width: 100%;
  height: 100%;
}
#singleTouchControls {
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 3;
  width: 100%;
  height: 100%;
  display: none;
}
#stcontrol {
  background: url(assets/arrows.png) no-repeat center;
}
#singleTouchControls .canvas {
  position relative;
  z-index: 4;
  border: 2px solid yellow;
}
#controlArea {
  position: relative;
  height: 90%;
}
#shipArea {
  position: absolute;
  top: 0px;
  left: 0px;
  border: 1px solid cyan;
  z-index: 500;
}
#ship {
  position: absolute;
  left: 25%;
  top: 25%;
  width: 50%;
  height: auto;
}
#controls {
  position: absolute;
  top: 0px;
  left: 0px;
  border: 1px solid yellow;
}
#keyControls {
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 3;
  width: 100%;
  height: 100%;
  display: none;
}
.move {
  float: left;
  width: 50%;
  height: 100%;
  vertical-align: middle;
  color: rgba(255, 255, 255, 0.5); /* black; */
  gbackground-color: rgba(255, 255, 255, 0.2);
  display: table-cell;
}
#tcmove.move, #tcfire.fire {
  width: 100%
}
.fire {
  float: right;
  width: 50%;
  height: 100%;
  vertical-align: middle;
  color: rgba(255, 255, 255, 0.75); /* white; */
  gbackground-color: rgba(0, 0, 0, 0.2);
}
#singleTouchControls .stmove {
  width: 100%;
  height: 100%;
}
#top {
  position: absolute;
  top: 0px;
  left: 0px;
  gz-index: 4;
  width: 100%;
  height: 100%;
}
#text {
  height: 10%;
  background-color: blue;
}
#input {
  display: none;
}
#disconnected {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  display: none;
  background-color: black;
  color: white;
  text-align: center;
  z-index: 1000
}
</style>
<link rel="stylesheet" media="all and (max-device-width: 1024px) and (orientation:portrait)" href="tablet-portrait.css">
<link rel="stylesheet" media="all and (max-device-width: 1024px) and (orientation:landscape)" href="tablet-landscape.css">
<link rel="stylesheet" media="all and (max-device-width: 900px) and (orientation:portrait)" href="phone-portrait.css">
<link rel="stylesheet" media="all and (max-device-width: 900px) and (orientation:landscape)" href="phone-landscape.css">
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="monitor.css">
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="ships.js"></script>
<script type="text/javascript" src="tdl/base.js"></script>
<script>
tdl.require('audio');
tdl.require('tdl.log');
window.onload = main;

var g_name = "";
var g_socket;
var g_turn = 0;
var g_oldTurn = 0;
var g_left = false;
var g_right = false;
var g_fire = false;
var g_keyState = {};
var g_oldKeyState = {};
var g_dirTouchStart = 0;
var g_numTouches = 0;
var g_ctx = 0;
var g_canvas;
var g_startX;
var g_startY;
var g_startTime;
var g_state = ""
var g_count;
var g_playerColor = "black";
var g_playerStyle;
var g_sendQueue = [];

function $(id) {
  return document.getElementById(id);
}

function logTo(id, str) {
  var c = $(id);
  var d = document.createElement("div");
  d.appendChild(document.createTextNode(str));
  c.appendChild(d);
  while(d.children.length > 6) {
    d.removeChild(d.firstChild);
  }
}

function log() {
  var s = ""
  for (var ii = 0; ii < arguments.length; ++ii) {
    s += arguments[ii].toString();
  }
  logTo("console", s);
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}

function connect(server, port) {
  if (!window.io) {
    g_socket = {
      send: function() { }
    };
    return;
  }
  var url = "http://" + window.location.host;
  g_sendQueue = [];
  g_socket = io.connect(url);
  g_socket.on('connect', connected);
  g_socket.on('message', function(obj) {
    processMessage(obj);
  });
  g_socket.on('disconnect', disconnected);
}

function connected() {
  for (var ii = 0; ii < g_sendQueue.length; ++ii) {
    g_socket.emit('message', g_sendQueue[ii]);
  }
  g_sendQueue = [];
  tdl.log("connected");
  $("disconnected").style.display = "none";
}

function disconnected() {
  tdl.log("disconnected");
  $("disconnected").style.display = "block";
}

function sendCmd(cmd, data) {
  var msg = {
    cmd: cmd,
    data: data
  };
  if (g_socket.readyState == WebSocket.CONNECTING) {
    g_sendQueue.push(msg);
  } else {
    g_socket.emit('message', msg);
  }
}


g_states = {
  launch: function() {
    --g_count;
    var e = $("surface");
    if (g_count > 0) {
      e.style.backgroundColor = (g_count % 2) ? "#0f0" : "#fff";
      setTimeout(process, 100);
    } else {
      e.style.backgroundColor = g_playerColor;
    }
  },

  die: function() {
    --g_count;
    var e = $("surface");
    if (g_count > 0) {
      e.style.backgroundColor = (g_count % 2) ? "#f00" : "#ff0";
      setTimeout(process, 100);
    } else {
      e.style.backgroundColor = g_playerColor;
    }
  }
};

function process() {
  g_states[g_state]();
};

function processMessage(msg) {
  switch (msg.cmd) {
  case 'setColor':
    //var e = $("surface");
    //e.style.backgroundColor = msg.color;
    var canvas = document.createElement("canvas");
    canvas.width = 150;
    canvas.height = 150;
    var xOff = canvas.width / 2;
    var yOff = canvas.height / 2;
    var ctx = canvas.getContext("2d");
    var styleName = ships.styles[msg.style];
    for (var yy = -2; yy <= 2; ++yy) {
      for (var xx = -2; xx <=2; ++xx) {
        ships.drawShip(ctx, xx + xOff, yy + yOff, Math.PI, "#000");
      }
    }
    ships[styleName](ctx, xOff, yOff, Math.PI, msg.color);
    $("ship").src = canvas.toDataURL();
    //e.style.backgroundImage = "url(" + canvas.toDataURL() + ")";
    break;
  case 'setName':
    g_name = msg.name;
    $('msg').innerHTML = "Name: " + g_name + " -- click to edit";
    $('msg').style.color = '#FFF';
    $('input').value = g_name;
    break;
  case 'kill':
    $('msg').innerHTML = 'Killed ' + msg.killed;
    $('msg').style.color = '#0FF';
    break;
  case 'die':
    audio.play_sound('explosion');
    $('msg').innerHTML = (msg.crash ? 'Crashed into ' : 'Killed by ') + msg.killer;
    $('msg').style.color = '#F00';
    g_state = "die";
    g_count = 20;
    setTimeout(process, 100);
    break;
  case 'launch':
    audio.play_sound('launching');
    $('msg').innerHTML = 'Launch!';
    $('msg').style.color = '#FF0';
    g_state = "launch";
    g_count = 30;
    setTimeout(process, 100);
    break;
  case 'queue':
    $('msg').innerHTML = msg.count > 0 ?
        (msg.count.toString() + " ahead of you") : "Next Up";
    $('msg').style.color = '#FFF';
    break;
  }
}

function debugTouch(label, event) {
  var allTouches = event.touches;
  logTo("status", label);
  for (var ii = 0; ii < allTouches.length; ++ii) {
    var touch = allTouches[ii];
    logTo("status", "  " + ii + ": " + touch.pageX + ", " + touch.pageY +
          " cw: " + event.target.clientWidth +
          " ch: " + event.target.clientHeight);
  }
  var s = $("status");
  s.scrollTop = s.scrollHeight;
}

function touchMoveStart(event) {
  event.preventDefault();
  var allTouches = event.touches;
  for (var ii = 0; ii < allTouches.length; ++ii) {
    ++g_numTouches;
    var touch = allTouches[ii];
    g_dirTouchStart = touch.pageX;
    break;
  }

  //debugTouch("start", event);
}

function touchMoveMove(event) {
  event.preventDefault();
  //debugTouch("move", event);
  var allTouches = event.touches;
  for (var ii = 0; ii < allTouches.length; ++ii) {
    var touch = allTouches[ii];
    var dx = touch.pageX - g_dirTouchStart;
    //logTo("status", dx)
    var fudge = 10
    if (dx < -fudge) {
      if (!g_left) {
        g_left = 1;
        g_right = 0;
        sendCmd("update", {
            cmd: 'turn',
            turn: -1
        });
      }
    } else if (dx > fudge) {
      if (!g_right) {
        g_left = 0;
        g_right = 1;
        sendCmd("update", {
            cmd: 'turn',
            turn: 1
        });
      }
    } else {
      if (g_right || g_left) {
        g_left = 0;
        g_right = 0;
        sendCmd("update", {
            cmd: 'turn',
            turn: 0
        });
      }
    }
    break;
  }
}

function touchMoveEnd(event) {
  event.preventDefault();
  if (g_right || g_left) {
    g_left = 0;
    g_right = 0;
    sendCmd("update", {
        cmd: 'turn',
        turn: 0
    });
  }
  //debugTouch("end", event);
}

function touchMoveCancel(event) {
  touchMoveEnd(event)
}

function touchFireStart(event) {
  event.preventDefault();
  if (!g_fire) {
    g_fire = true;
    sendCmd("update", {
        cmd: 'fire',
        fire: 1
    });
  }

  //debugTouch("start", event);
}

function touchFireMove(event) {
  event.preventDefault();
  //debugTouch("move", event);
}

function touchFireEnd(event) {
  event.preventDefault();
  if (g_fire) {
    g_fire = false;
    sendCmd("update", {
        cmd: 'fire',
        fire: 0
    });
  }
  //debugTouch("end", event);
}

function touchFireCancel(event) {
  touchFireEnd(event);
  //debugTouch("cancel", event);
}

/**
 * Returns the absolute position of an element for certain browsers.
 * @param {HTML Element} element The element to get a position for.
 * @return {Object} An object containing x and y as the absolute position
 *     of the given element.
 */
var getAbsolutePosition = function(element) {
  var r = { x: element.offsetLeft, y: element.offsetTop };
  if (element.offsetParent) {
    var tmp = getAbsolutePosition(element.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

var getRelativeCoordinates = function(reference, event) {
  // Use absolute coordinates
  var pos = getAbsolutePosition(reference);
  x = event.pageX - pos.x;
  y = event.pageY - pos.y;
  return { x: x, y: y };
};

function updateTarget(element, x, y) {
  var centerX = element.clientWidth / 2;
  var centerY = element.clientHeight / 2;
  var dx = x - centerX;
  var dy = y - centerY;
  var direction = Math.atan2(dy, dx);
  sendCmd("update", {
      cmd: 'target',
      target: (direction + Math.PI / 2 * 3) % (Math.PI * 2)
  });

  var ctx = g_ctx;
  ctx.clearRect(0, 0, g_canvas.width, g_canvas.height);
  ctx.save();
  ctx.translate(g_canvas.width / 2, g_canvas.height / 2);
  ctx.rotate(direction - Math.PI / 2);
  ctx.fillStyle = "#FF0";
  ctx.beginPath();
  ctx.closePath();
  ctx.moveTo(10, 0);
  ctx.lineTo(10, 50);
  ctx.lineTo(30, 50);
  ctx.lineTo(0, 70);
  ctx.lineTo(-30, 50);
  ctx.lineTo(-10, 50);
  ctx.lineTo(-10, 00);
  ctx.closePath();
  ctx.fill();
  ctx.restore();

};

function singleTouchStart(event) {
  event.preventDefault();
  var m = getRelativeCoordinates(event.target, event.touches[0]);
  updateTarget(event.target, m.x, m.y);
  g_startTime = (new Date()).getTime();
}

function singleTouchMove(event) {
  event.preventDefault();
  var m = getRelativeCoordinates(event.target, event.touches[0]);
  updateTarget(event.target, m.x, m.y);
}

function singleTouchEnd(event) {
  event.preventDefault();
  var now = (new Date()).getTime();

  if (now - g_startTime < 200) {
    sendCmd("update", {
        cmd: 'fire',
        fire: 1
    });
    sendCmd("update", {
        cmd: 'fire',
        fire: 0
    });
  }
}

function singleTouchCancel(event) {
  singleTouchEnd(event);
}

function handleKeyDown(keyCode, state) {
  switch(keyCode) {
  case 37: // left
    if (!g_left) {
      g_left = true;
      sendCmd("update", {
          cmd: 'turn',
          turn: -1
      });
    }
    break;
  case 39: // right
    if (!g_right) {
      g_right = true;
      sendCmd("update", {
          cmd: 'turn',
          turn: 1
      });
    }
    break;
  case 90: // z
    if (!g_fire) {
      g_fire = true;
      sendCmd("update", {
          cmd: 'fire',
          fire: 1
      });
    }
    break;
  }
}

function handleKeyUp(keyCode, state) {
  switch(keyCode) {
  case 37: // left
    g_left = false;
    sendCmd("update", {
        cmd: 'turn',
        turn: (g_right) ? 1 : 0
    });
    break;
  case 39: // right
    g_right = false;
    sendCmd("update", {
        cmd: 'turn',
        turn: (g_left) ? -1 : 0
    });
    break;
  case 90: // z
    g_fire = false;
    sendCmd("update", {
        cmd: 'fire',
        fire: 0
    });
    break;
  }
}

function updateKey(keyCode, state) {
  g_keyState[keyCode] = state;
  if (g_oldKeyState != g_keyState) {
    g_oldKeyState = state;
    if (state) {
      handleKeyDown(keyCode);
    } else {
      handleKeyUp(keyCode);
    }
  }
}

function keyUp(event) {
  //logTo("status", "keyUp: " + event.keyCode);
  var s = $("status");
  s.scrollTop = s.scrollHeight;
  updateKey(event.keyCode, false);
}

function keyDown(event) {
  //logTo("status", "keyDown: " + event.keyCode);
  var s = $("status");
  s.scrollTop = s.scrollHeight;
  updateKey(event.keyCode, true);
}

function enterName(event) {
  $('msg').style.display = "none";
  $('msg').style.color = "#FFF";
  $('input').style.display = "block";
  $('input').focus();
  sendCmd("update", {
      cmd: 'busy',
      busy: true
  });
}

function sendName() {
  sendCmd("update", {
      cmd: 'name',
      name: g_name
  });
  $('msg').innerHTML = g_name;
}

function finishSendName(event) {
  g_name = $('input').value.replace(/[<>]/g, '');
  createCookie("name", g_name, 90);
  tdl.log("name: ", g_name);
  sendName(event);
  $('msg').style.display = "block";
  $('input').style.display = "none";
  sendCmd("update", {
      cmd: 'busy',
      busy: false
  });
}

function reloadPage() {
  window.location.reload();
}

function main() {
  connect();

  audio.init({
    explosion: {
      filename: "assets/explosion.ogg",
      samples: 1,
    },
    launching: {
      filename: "assets/launching.ogg",
      samples: 1,
    }
  });

  ships.setShipSize(70);

  // Get the name user set before.
  g_name = readCookie("name");
  if (!g_name) {
    g_name = "";
  }
  // Note: If the name is "" server will send a name
  sendName();

  var haveTouch = 'ontouchstart' in document

  var surface = $("top");
  if (haveTouch) {
    if (navigator.userAgent.indexOf("Android") >= 0 && !window.opera) {
      var singleTouchControls = $("singleTouchControls");
      var touchControls = $("touchControls");
      singleTouchControls.style.display = "block";
      touchControls.style.display = "none";
      var stcontrol = $("stcontrol");
      stcontrol.addEventListener("touchstart", singleTouchStart, false);
      stcontrol.addEventListener("touchmove", singleTouchMove, false);
      stcontrol.addEventListener("touchend", singleTouchEnd, false);
      stcontrol.addEventListener("touchcancel", singleTouchCancel, false);
      g_canvas = document.getElementsByTagName("canvas")[0];
      g_ctx = g_canvas.getContext("2d");
    } else {
      var tcmove = $("tcmove");
      var tcfire = $("tcfire");
      tcmove.addEventListener("touchstart", touchMoveStart, false);
      tcmove.addEventListener("touchmove", touchMoveMove, false);
      tcmove.addEventListener("touchend", touchMoveEnd, false);
      tcmove.addEventListener("touchcancel", touchMoveCancel, false);
      tcfire.addEventListener("touchstart", touchFireStart, false);
      tcfire.addEventListener("touchmove", touchFireMove, false);
      tcfire.addEventListener("touchend", touchFireEnd, false);
      tcfire.addEventListener("touchcancel", touchFireCancel, false);
    }
  } else {
    var keyControls = $("keyControls");
    var touchControls = $("touchControls");
    keyControls.style.display = "block";
    touchControls.style.display = "none";
    window.addEventListener("keyup", keyUp, false);
    window.addEventListener("keydown", keyDown, false);
  }
  $('msg').addEventListener("click", enterName, false);
  $('input').addEventListener("change", finishSendName, false);
  $('input').addEventListener("blur", finishSendName, false);
  $('reload').addEventListener("click", reloadPage, false);
}
</script>
</head>
<body>
<div id="surface">
  <img id="ship" src="assets/waiting.png" />
  <div id="status"></div>
  <div id="console"></div>
</div>
<div id="top">
  <div id="text">
    <div id="msg">msg</div>
    <input type="text" id="input" />
  </div>
  <div id="controlArea">
    <div id="touchControls">
      <!-- FUCK U CSS ... 2 hours fucking with you you suck! -->
      <table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%">
        <tr>
          <td width="50%">
        <div id="tcmove" class="move">
          <div class="instruction">Drag Left/Right here to Steer</div>
        </div>
          </td>
          <td width="50%">
        <div id="tcfire" class="fire">
          <div class="instruction">Press here to Fire</div>
        </div>
          </td>
        </tr>
      </table>
    </div>
    <div id="singleTouchControls">
      <div class="stmove">
        <table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%">
        <tr height="10px">
          <td>
            <div class="instruction">Press to Steer, Tap to Fire</div>
          </td>
        </tr>
        <tr>
          <td valign="middle" align="center" id="stcontrol">
              <center>
                <canvas class="canvas" width="150" height="150"></canvas>
              <center>
          </td>
        </tr>
        </table>
      </div>
    </div>
    <div id="keyControls">
      <div class="move">
        <div class="instruction">Press Cursor Keys to Steer</div>
      </div>
      <div class="fire">
        <div class="instruction">Press Z to Fire</div>
      </div>
    </div>
  </div>
  <div id="disconnected">
    <div class="instruction">Disconnected</div>
    <div class="instruction" id="reload">click to reload</div>
  </div>
</div>
</body>
</html>


